

import UIKit
import UIKit
import Moya
import KeychainAccess

struct QueryStringPair {
    var key: String
    var value: Any
}

class FAMNetHeaderConfig: NSObject {
    @objc static let shared = FAMNetHeaderConfig()
    @objc var rts:String = ""
    @objc var appId:String = ""
    @objc var appKey:String = ""
    
    fileprivate var uuidKey = Bundle.main.bundleIdentifier ?? ""
    fileprivate let keychain = Keychain(service: Bundle.main.bundleIdentifier ?? "")
    
    @objc func FAM_setupConfig(appId:String,appkey:String) -> Void {
        self.appId = appId
        self.appKey = appkey
    }
    
    func FAM_getCommonHeaders(otherParams:[String:String]) -> [String:String] {
        let headers = [
            "app_id":self.appId,
            "Content-Type": "application/json",
            "rts": self.rts,
            "encrypt":FAM_getEncrypRTS(params: otherParams)
        ]
        return headers
    }
    
    func FAM_getEncrypRTS(params: [String:Any]) -> String {
        var additionalParameters = FAM_fillParams(temp: params)
        let sign = FAMMD5().MD5(FAMNetHeaderConfig.FAM_calculateSignValue(additionalParameters,appKey: FAMNetHeaderConfig.shared.appKey)).lowercased()
        additionalParameters["sign"] = sign
        return FAMEncryptTool.encrypt(content: additionalParameters)
    }
    
    func FAM_getEncryBody(params:Any) -> [String:Any] {
        var additionalParameters = ["rts":self.rts]
        additionalParameters["data"] = FAMEncryptTool.convertToJSONString(object: params)
        let sign = FAMMD5().MD5(FAMNetHeaderConfig.FAM_calculateSignValue(additionalParameters,appKey: FAMNetHeaderConfig.shared.appKey)).lowercased()
        additionalParameters["sign"] = sign
        return ["data":FAMEncryptTool.encrypt(content: additionalParameters)]
    }
    
    
    func FAM_fillParams(temp:[String:Any]) -> [String:Any] {
        
        var parameters:[String:Any] = [FAM_OCString(_2753689520):FAM_getUUID()]
        
        parameters[FAM_OCString(_475199832)] = "iPhone"
        
        if let ipAddress = FAMNetHeaderConfig.FAM_ipAddress {
            parameters["mac"] = ipAddress
        }
        
        if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
            parameters[FAM_OCString(_1574768987)] = version
        }
        parameters["idfv"] = UIDevice.current.identifierForVendor?.uuidString
        
        parameters[FAM_OCString(_822707298)] = FAMNetHeaderConfig.FAM_systemLang
        
        parameters[FAM_OCString(_711719256)] = rts
        
        parameters[FAM_OCString(_3616895705)] = FAMNetHeaderConfig.FAM_deviceName
        
        parameters[FAM_OCString(_675401137)] = FAMNetHeaderConfig.FAM_systemVersion
        
        parameters["platform"] = "ios"
        for (key,value) in temp {
            parameters[key] = value
        }
        return parameters
    }
    
    static var FAM_deviceName: String {
        return FAMNetHeaderConfig.shared.FAM_phoneModel
    }
    
    static var FAM_systemVersion: String {
        return UIDevice.current.systemVersion
    }
    
    
    func FAM_getUUID() -> String {
        if let uuidString = keychain[uuidKey] {
            return uuidString;
        } else {
            let uuidStr = FAM_uuidString()
            keychain[uuidKey] = uuidStr
            return uuidStr
        }
    }
    
    static var FAM_systemLang: String {
        let arrLang = NSLocale.preferredLanguages
        return arrLang.first ?? "en"
    }
    
    static var FAM_ipAddress: String? {
        var ipAddress: String?
         let host = CFHostCreateWithName(nil, "localhost" as CFString).takeRetainedValue()
         if let addresses = CFHostGetAddressing(host, nil) {
             let addressesArray = addresses.takeUnretainedValue() as NSArray
             if let address = addressesArray.firstObject as? NSData {
                 var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                 if getnameinfo(address.bytes.assumingMemoryBound(to: sockaddr.self),
                                socklen_t(address.length),
                                &hostname, socklen_t(hostname.count),
                                nil, socklen_t(0), NI_NUMERICHOST) == 0 {
                     ipAddress = String(cString: hostname)
                 }
             }
         }
         return ipAddress
    }
    
    public func FAM_fillRts() {
        let rts = Date().timeIntervalSince1970 * 1000
        let rtsString = "\(rts)".prefix(13)
        FAMNetHeaderConfig.shared.rts = String(rtsString)
    }
    
    func FAM_uuidString() -> String {
        let uuid = UUID().uuidString
        return uuid
    }
    
    class func FAM_calculateSignValue(_ params: [String: Any], appKey: String) -> String {
        let queryKeyValues = FAM_queryString(with: params, joinString: "&")
        let signString = "\(queryKeyValues)&key=\(appKey)"
        return signString
    }

    class func FAM_queryString(with parameters: [String: Any], joinString: String) -> String {
        var mutablePairs = [String]()
        for item in FAM_queryStringPairs(fromKeyAndValue: nil, value: parameters) {
            mutablePairs.append("\(item.key)=\(item.value)")
        }
        return mutablePairs.joined(separator: joinString)
    }
    
    static func FAM_queryStringPairs(fromKeyAndValue key: String?, value: Any) -> [QueryStringPair] {
        var mutableQueryStringComponents = [QueryStringPair]()
        let sortDescriptor = NSSortDescriptor(key: "description", ascending: true, selector: #selector(NSString.compare(_:)))
        if let dictionary = value as? [String: Any] {
            for nestedKey in dictionary.keys.sorted(by: { $0.compare($1) == .orderedAscending }) {
                if let nestedValue = dictionary[nestedKey] {
                    let newKey = key != nil ? "\(key!)[\(nestedKey)]" : nestedKey
                    mutableQueryStringComponents.append(contentsOf: FAM_queryStringPairs(fromKeyAndValue: newKey, value: nestedValue))
                }
            }
        } else if let array = value as? [Any] {
            for nestedValue in array {
                let newKey = "\(key ?? "")[]"
                mutableQueryStringComponents.append(contentsOf: FAM_queryStringPairs(fromKeyAndValue: newKey, value: nestedValue))
            }
        } else if let set = value as? Set<AnyHashable> {
            for obj in set.sorted(by: { ($0 as! NSString).compare(($1 as! NSString) as String) == .orderedAscending }) {
                mutableQueryStringComponents.append(contentsOf: FAM_queryStringPairs(fromKeyAndValue: key, value: obj))
            }
        } else {
            mutableQueryStringComponents.append(QueryStringPair(key: key ?? "", value: value))
        }
        
        return mutableQueryStringComponents
    }
    
    
    var FAM_phoneModel: String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8 , value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        
        switch identifier {
        case "iPod5,1":                                 return "iPod Touch 5"
        case "iPod7,1":                                 return "iPod Touch 6"
        case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return "iPhone 4"
        case "iPhone4,1":                               return "iPhone 4s"
        case "iPhone5,1", "iPhone5,2":                  return "iPhone 5"
        case "iPhone5,3", "iPhone5,4":                  return "iPhone 5c"
        case "iPhone6,1", "iPhone6,2":                  return "iPhone 5s"
        case "iPhone7,2":                               return "iPhone 6"
        case "iPhone7,1":                               return "iPhone 6 Plus"
        case "iPhone8,1":                               return "iPhone 6s"
        case "iPhone8,2":                               return "iPhone 6s Plus"
        case "iPhone8,4":                               return "iPhone SE (1st generation)"
        case "iPhone9,1", "iPhone9,3":                  return "iPhone 7"
        case "iPhone9,2", "iPhone9,4":                  return "iPhone 7 Plus"
        case "iPhone10,1", "iPhone10,4":                return "iPhone 8"
        case "iPhone10,5", "iPhone10,2":                return "iPhone 8 Plus"
        case "iPhone10,3", "iPhone10,6":                return "iPhone X"
        case "iPhone11,2":                              return "iPhone XS"
        case "iPhone11,4", "iPhone11,6":                return "iPhone XS MAX"
        case "iPhone11,8":                              return "iPhone XR"
        case "iPhone12,1":                              return "iPhone 11"
        case "iPhone12,3":                              return "iPhone 11 pro"
        case "iPhone12,5":                              return "iPhone 11 Pro Max"
        case "iPhone12,8":                              return "iPhone SE (2nd generation)"
        case "iPhone13,1":                              return "iPhone 12 mini"
        case "iPhone13,2":                              return "iPhone 12"
        case "iPhone13,3":                              return "iPhone 12 Pro"
        case "iPhone13,4":                              return "iPhone 12 Pro Max"
        case "iPhone14,4":                              return "iPhone 13 mini"
        case "iPhone14,5":                              return "iPhone 13"
        case "iPhone14,2":                              return "iPhone 13 Pro"
        case "iPhone14,3":                              return "iPhone 13 Pro Max"
        case "iPhone14,6":                              return "iPhone SE (3rd generation)"
        case "iPhone14,7":                              return "iPhone 14"
        case "iPhone14,8":                              return "iPhone 14 Plus"
        case "iPhone15,2":                              return "iPhone 14 Pro"
        case "iPhone15,3":                              return "iPhone 14 Pro Max"
        case "iPhone15,4":                              return "iPhone 15"
        case "iPhone15,5":                              return "iPhone 15 Plus"
        case "iPhone16,1":                              return "iPhone 15 Pro"
        case "iPhone16,2":                              return "iPhone 15 Pro Max"
            
            
        case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
        case "iPad3,1", "iPad3,2", "iPad3,3":           return "iPad 3"
        case "iPad3,4", "iPad3,5", "iPad3,6":           return "iPad 4"
        case "iPad6,11", "iPad6,12":                    return "iPad 5"
        case "iPad7,5", "iPad7,6":                      return "iPad 6"
        case "iPad7,11", "iPad7,12":                    return "iPad 7"
        case "iPad11,6", "iPad11,7":                    return "iPad 8"
        case "iPad12,1", "iPad12,2":                    return "iPad 9"

        case "iPad4,1", "iPad4,2", "iPad4,3":           return "iPad Air"
        case "iPad5,3", "iPad5,4":                      return "iPad Air 2"
        case "iPad11,3", "iPad11,4":                    return "iPad Air 3"
        case "iPad13,1", "iPad13,2":                    return "iPad Air 4"
        case "iPad13,16", "iPad13,17":                  return "iPad Air 5"
        
        case "iPad2,5", "iPad2,6", "iPad2,7":           return "iPad Mini"
        case "iPad4,4", "iPad4,5", "iPad4,6":           return "iPad Mini 2"
        case "iPad4,7", "iPad4,8", "iPad4,9":           return "iPad Mini 3"
        case "iPad5,1", "iPad5,2":                      return "iPad Mini 4"
        case "iPad11,1", "iPad11,2":                    return "iPad Mini 5"
        case "iPad14,1", "iPad14,2":                    return "iPad Mini 6"
        case "iPad6,7", "iPad6,8", "iPad6,3", "iPad6,4", "iPad7,1", "iPad7,2", "iPad7,3", "iPad7,4", "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4", "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8", "iPad8,9", "iPad8,10", "iPad8,11", "iPad8,12":         return "iPad Pro"
        case "AppleTV5,3":                              return "Apple TV"
        case "i386", "x86_64","arm64":                          return "Simulator"
        default:                                        return identifier
        }
    }
}
